"use strict"

const run = require('./run').await_for
const _ = require('lodash/fp')
const fetch = require('node-fetch')
const cheerio = require('cheerio')
const e = raw => raw.replace(/([\\'"])/gm, '\\$1')
const e_url = raw => raw//.replace(/(https:\/\/)/gm, 'http://')
const opt = {
    timeout: 5000,
}

const iterator = function* (cate) {
    //花椒 url格式： http://www.huajiao.com/category/${cate_id}?pageno=${page}

    const url = `http://www.huajiao.com/category/`;
    let page = 1
    let page_count = 0

    const format = result => {
        let $ = cheerio.load(result)
        let data = [];

        if (page_count === 0) {
            page_count = parseInt($('ul.pagination>li.last').attr('tabindex')) - 1
        }

        $('ul.g-list2 li:not(:has(i.replay-icon))').map((i, t) => {
            const raw_name = $(t).find('div.nickname').text()
            const name = e(raw_name)
            const cover = $(t).find('div.pic img').attr('src')
            let id = 0;
            for (let i = 0; i < raw_name.length; i++) {
                let code = raw_name.charCodeAt(i)
                if (code < 0xFFFFFF)
                    id += code.toString(32)
            }

            data.push({
                live_id: 9
                , name: name
                , room_name: name
                , online: isNaN(parseInt($(t).find('span.num').text())) ? 0 : parseInt($(t).find('span.num').text())
                , id: '9_' + id.toString(16)
                , room_id: $(t).find('a').attr('href').replace(/[^\d]+/, '')
                , url: 'http://www.huajiao.com' + $(t).find('a').attr('href')
                , cover: cover
                , avatar: cover
                , category_id: cate.id
                , category_name: cate.name
                , category_url: `http://www.huajiao.com`
            })
        })

        return data
    }

    while ((!page_count || page < page_count) && page < 20) {
        yield fetch(`${url}${cate.id}?pageno=${page++}`, opt)
            .then(_ => _.text())
            .then(format)
    }
}

module.exports = {
    run: () => {
        const cates = [
            {
                id: 1,
                name: '娱乐明星'
            },
            {
                id: 2,
                name: '女神驾到'
            },
            {
                id: 5,
                name: '网络表演'
            },
            {
                id: 999,
                name: '校园女生'
            },
            {
                id: 1001,
                name: '音乐达人'
            },

        ]

        return Promise.all(cates.map(cate => run(iterator(cate)))).then(_.flattenDeep).then(_.uniqBy('id'))
    }
}